from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
import cforms
from models import *

def golfer( request, golfer_key ):
	try:
		golfer = Golfer.get(golfer_key)
		form = cforms.GolferForm(instance=golfer)
		verb = "update"
	except:
		golfer = None
		form = cforms.GolferForm()
		verb = "create"
		
	if request.method == 'POST':
		form = cforms.GolferForm(request.POST, instance=golfer)
		if form.is_valid():
			golfer = form.save()
			return HttpResponseRedirect(golfer.get_absolute_url())
 
	
	template_values = {'form':form, 'verb':verb, 'golfer':golfer}
  	return render_to_response('caddy/golfer.html', template_values)	

def golfers (request):
	
  	return render_to_response('caddy/golfers.html', {"golfers":list(Golfer.all())})

def course (request, course_key):
	holes = []
	try:
		course = Course.get(course_key)
		for hole in course.holes:
			holes.append(cforms.HoleForm(course=course, instance=hole))
		if holes:
			form = cforms.CourseForm(instance=course)
		else:
			form = cforms.CourseFormWithHoleCount(instance=course)
		verb = "update"
	except:
		course = None
		form = cforms.CourseForm(request.POST)
		verb = "create"
		
	
	if request.method == 'POST':
		form = cforms.CourseFormWithHoleCount(request.POST, instance=course)
		if form.is_valid():
			course = form.save()
			if form.clean_data.has_key('hole_count'):
				for i in range(1,int(form.clean_data['hole_count'])+1):
					Hole(course=course, number=i, par=3, name="Hole %d" % i).put()
			return HttpResponseRedirect(course.get_absolute_url())
	
	
	
	template_values = {'form':form, 'verb':verb, 'course':course, 'holes':holes}
  	return render_to_response('caddy/course.html', template_values)


def courses (request):
	
  	return render_to_response('caddy/courses.html', {"courses":list(Course.all())})
	

def hole( request, hole_id ):
	hole_id = int( hole_id )
  	template_values = {
      'course': "Redan",
      'hole': hole_id,
      'strokes' : range( 1, 10 ),
      'players' : ["NRB", "BCB"],
      'par' : 4,
      'prev': hole_id - 1,
      'next': hole_id + 1
      }
  	
  	return render_to_response('caddy/hole.html', template_values)
